import { constantRouterMap } from "@/router";

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0);
  } else {
    return true;
  }
}
const cutArray=function(data,cc){
  let rt = [];
  cc.forEach((el,index)=>{
    if(data.indexOf(el.name)!=-1){
      rt.push(el);
      if(el.children && el.children.length){
        el.children = cutArray(data,el.children);
      }
    }
  });
  return rt;
}
const permission = {
  state: {
    routers: [],
    currentMenuIndex: 0,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = routers;// constantRouterMap.concat(routers);
    },
    SET_MENU_INDEX(state, idx) {
      state.currentMenuIndex = idx;
    }
  },
  actions: {
    changeMenuIndex({ commit }, idx) {
      commit("SET_MENU_INDEX", idx);
    },
    GenerateRoutes({ commit }, data) {
      let cc = [].concat(JSON.parse(JSON.stringify(constantRouterMap)));
      let yy = cutArray(data,cc);
      commit("SET_ROUTERS",yy);
      commit('SET_MENU_INDEX',0);
      // return new Promise(resolve => {
      //   const { roles } = data;
      //   let accessedRouters;
      //   if (roles.indexOf("admin") >= 0) {
      //     accessedRouters = asyncRouterMap;
      //   } else {
      //     accessedRouters = filterAsyncRouter(asyncRouterMap, roles);
      //   }
      //   commit("SET_ROUTERS", accessedRouters);
      //   resolve();
      // });
    }
  }
};

export default permission;
